package com.xzone.material.security.authentication

import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.MediaType
import org.springframework.security.authentication.*
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.stereotype.Component

@Component
class MyAuthenticationFailureHandler : AuthenticationFailureHandler {
    override fun onAuthenticationFailure(
        request: HttpServletRequest, response: HttpServletResponse, exception: AuthenticationException
    ) {
        val mapper = ObjectMapper()

        val result = HashMap<String, Any>()

        when (exception) {
            is AccountExpiredException -> {
                // 账号过期
                result["msg"] = "[登录失败] - 用户[{}]账号过期"
            }

            is BadCredentialsException -> {
                // 密码错误
                result["msg"] = "[登录失败] - 用户[{}]密码错误"
            }

            is CredentialsExpiredException -> {
                // 密码过期
                result["msg"] = "[登录失败] - 用户[{}]密码过期"
            }

            is DisabledException -> {
                // 用户被禁用
                result["msg"] = "[登录失败] - 用户[{}]被禁用"
            }

            is LockedException -> {
                // 用户被锁定
                result["msg"] = "[登录失败] - 用户[{}]被锁定"
            }

            is InternalAuthenticationServiceException -> {
                // 内部错误
                result["msg"] = "[登录失败] - [%s]内部错误"
            }

            else -> {
                // 其他错误
                result["msg"] = "[登录失败] - [%s]其他错误"
            }
        }

        response.characterEncoding = Charsets.UTF_8.name()
        response.contentType = MediaType.APPLICATION_JSON_VALUE
        response.writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result))
    }
}